package com.example.yupao_project.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.yupao_project.entity.User;
import com.example.yupao_project.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 定时实现缓存预热
 * @author: 杰
 * @date: 2024/5/10 17:36
 */
@Component
@Slf4j
public class PreCacheJob {
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private List<Long> mainUserList = Arrays.asList(1L);

    //每天执行
    @Scheduled(cron = "05 36 * * * *")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("yupao:precachejob:docache:lock");
        try {
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                System.out.println("getLock:" + Thread.currentThread().getId());
                for (Long userId : mainUserList) {
                    String redisKey = String.format("yupao_project:user:recommend:%s", userId);
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> pageList = userService.page(new Page<>(1, 20), queryWrapper);
                    //将查询的内容存入redis
                    try {
                        valueOperations.set(redisKey, pageList, 60, TimeUnit.SECONDS);
                    } catch (Exception e) {
                        log.info("存入缓存失败");
                    }
                }
                Thread.sleep(1000000);
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error", e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                if (lock.isHeldByCurrentThread()) {
                    System.out.println("unlock: " + Thread.currentThread().getId());
                    lock.unlock();
                }
            }
        }

    }
}
